from django.http import JsonResponse
import time
from django.utils.deprecation import MiddlewareMixin
from knight_api.models import AdminModel


class KDN(MiddlewareMixin):
    def process_request(self, req):
        print(req.path)
        if req.path != "/api/login":
            try:
                # print(req.META)
                token = req.META.get("HTTP_AUTHORIZATION").split(" ")[1]
                print('*'*50)
                print(token)
                print('*'*50)

                data = list(AdminModel.objects.filter(token=token).values())
                # print(data)
                if data is None:
                    return JsonResponse({"code": 400, "message": "token无效1"})
                elif float(data[0]["avatar"]) < time.time():
                    return JsonResponse({"code": 401, "message": "token过期"})
            except AttributeError:
                return JsonResponse({"code": 400, "message": "token无效2"})
            except IndexError:
                return JsonResponse({"code": 400, "message": "token无效3"})
